package com.example.hello.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


/**
 * <p>
 *
 * </p>
 *
 * @author 12071
 * @date 2022/8/1 14:27
 */
@Slf4j
@Aspect
@Component
public class RequestAspect {

    /**
     * 申明一个切点 里面是execution表达式
     */
    @Pointcut("execution(public * com.example.hello.controller.*Controller.*(..))")
    private void controllerAspect() {
    }

    @Before(value = "controllerAspect()")
    public void methodBefore(JoinPoint joinPoint) throws ClassNotFoundException {
        log.info("********** in AOP methodBefore");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        /* 打印请求内容 */
//        log.info("********** 请求地址: {}, method: {}", request.getRequestURI(), request.getMethod());
        log.info("********** 请求类方法: {}, args: {}", joinPoint.getSignature(), Arrays.toString(joinPoint.getArgs()));
        /* 获取连接点目标类名 */
        String targetName = joinPoint.getTarget().getClass().getName() ;
        /*根据连接点类的名字获取指定类*/
        Class<?> targetClass = Class.forName(targetName);
//        log.info("********** 连接点目标类名: {}", targetName);
    }

    @AfterReturning(returning = "o", pointcut = "controllerAspect()")
    public void methodAfterReturning(Object o){
        log.info("********** 返回内容: {}", o.toString());
    }


}
